using MongoDB.Driver;
using newsApi.Models;
using Microsoft.Extensions.Options;

namespace newsApi.Services;

public class NewsService
{
    private readonly IMongoCollection<News> _newsCollection;
    public NewsService(IOptions<NewsLibDatabaseSettings> newsLibDatabaseSettings)
    {
        var mongoClient = new MongoClient(
            newsLibDatabaseSettings.Value.ConnectionString);

        var mongoDatabase = mongoClient.GetDatabase(
            newsLibDatabaseSettings.Value.DatabaseName);

        _newsCollection = mongoDatabase.GetCollection<News>(
            newsLibDatabaseSettings.Value.NewsCollectionName);
    }
    public async Task<List<News>> GetAsync() =>
      await _newsCollection.Find(_ => true).ToListAsync();

    public async Task<News?> GetAsync(string id) =>
           await _newsCollection.Find(x => x.Id == id).FirstOrDefaultAsync();

    public async Task CreateNews(News newNews) =>
       await _newsCollection.InsertOneAsync(newNews);

    public async Task UpdateNews(string id, News updatedNews) =>
    await _newsCollection.ReplaceOneAsync(x => x.Id == id, updatedNews);
    public async Task RemoveNews(string id) =>
    await _newsCollection.DeleteOneAsync(x => x.Id == id);
}